/**
 * Copyright (c) 2017,安徽皖通科技股份有限公司 All rights reserved.
 *
 * @data:2017年10月16日
 * @author:MaShibo
 */
package com.wttech.dzzf.process.service.user;

import com.wtkj.vo.dzzf.base.kfwd.CardInfo;
import com.wtkj.vo.dzzf.base.kfwd.FundAccount;
import com.wttech.dzzf.process.dao.FundAccountInfoDao;
import com.wttech.dzzf.process.dao.TransferUserInfoDao;
import com.wttech.dzzf.process.service.base.BaseInfoService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;

import static com.wttech.dzzf.process.constant.UserConstants.OLD_OWNERTYPE_COMPANY;

/**
 * 填充资金账户信息服务
 *
 * @author MaShibo
 * @date 2017年10月16日
 */
@Service
public class FillAccountInfosService {


    private static final Logger LOGGER = LoggerFactory.getLogger(FillAccountInfosService.class);

    private static final int DEFAULT_PROCESSNUM = 10000;

    @Resource
    private FundAccountInfoDao fundAccountInfoDao;

    @Resource
    private TransferUserInfoDao transferUserInfoDao;

    @Resource
    private ThreadPoolTaskExecutor executor;

    @Resource
    private BaseInfoService baseInfoService;

    private void fillAccountInfos() {
        Integer total = fundAccountInfoDao.queryNormalFundAccountNum();
        LOGGER.info("共{}条正常的资金账户信息", total);
        int count = (int) Math.ceil((double) total / DEFAULT_PROCESSNUM);
        LOGGER.info("共需要执行{}次", count);
        List<Future<Void>> futures = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            int num = i + 1;
            LOGGER.info("第{}次开始执行", num);
            int startRow = (num - 1) * DEFAULT_PROCESSNUM + 1;
            int endRow = num * DEFAULT_PROCESSNUM;
            futures.add(executor.submit(() -> {
                List<FundAccount> fundAccounts1 = fundAccountInfoDao.queryNormalFundAccount(startRow, endRow);
                fundAccounts1.forEach(FillAccountInfosService.this::processSingleData);
                return null;
            }));
            LOGGER.info("第{}次执行结束", num);
        }
        baseInfoService.getFutureResult(futures);
        LOGGER.info("数据填充完毕");
        executor.shutdown();
    }

    private void processSingleData(FundAccount fundAccount) {
        List<CardInfo> cardInfos;
        try {
            cardInfos = transferUserInfoDao.queryCardInfosByFundAccount(fundAccount.getFundAccountId());
        } catch (Exception e1) {
            LOGGER.error(e1.getMessage(), e1);
            return;
        }
        if (CollectionUtils.isEmpty(cardInfos)) {
            return;
        }
        int ownerType = fundAccount.getOwnerType();
        String phoneNo = StringUtils.isBlank(fundAccount.getPhone()) ? fundAccount.getMobile() : fundAccount.getPhone();
        String agentIdNum = fundAccount.getAgentIdNum();
        Integer agentIdType = fundAccount.getAgentIdType();
        String relationName = fundAccount.getRelationName();
        String cardNo = null;
        for (CardInfo cardInfo : cardInfos) {
            if (StringUtils.isBlank(cardNo)) {
                cardNo = cardInfo.getCardNetID() + cardInfo.getECardNo();
            }
            if (StringUtils.isBlank(phoneNo) && StringUtils.isNotBlank(cardInfo.getPhoneNo())) {
                phoneNo = cardInfo.getPhoneNo();
            }
            if (ownerType == OLD_OWNERTYPE_COMPANY) {
                if (agentIdType == null && cardInfo.getCertifiType() != null) {
                    agentIdType = cardInfo.getCertifiType();
                }
                if (StringUtils.isBlank(agentIdNum) && StringUtils.isNotBlank(cardInfo.getCertifiNo())) {
                    agentIdNum = cardInfo.getCertifiNo();
                }
                if (StringUtils.isBlank(relationName) && StringUtils.isNotBlank(cardInfo.getName())) {
                    relationName = cardInfo.getName();
                }
            }
        }
        fundAccount.setPhone(phoneNo);
        if (ownerType == OLD_OWNERTYPE_COMPANY) {
            fundAccount.setAgentIdNum(agentIdNum);
            fundAccount.setAgentIdType(agentIdType);
            fundAccount.setRelationName(relationName);
        }
        try {
            transferUserInfoDao.updateTestObject(fundAccount);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            LOGGER.info(fundAccount.toString());
        }
    }

    public static void main(String[] args) {
        @SuppressWarnings("resource")
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        FillAccountInfosService service = context.getBean(FillAccountInfosService.class);
        service.fillAccountInfos();
    }
}
